package cn.wolfcode.rbac.shiro;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//自定义数据源Realm
@Component("crmRealm")
public class CRMRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper mapper;
    //提供授权相关信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取到登录用户从token中，拿到令牌
        Object principal =authenticationToken.getPrincipal();
        Employee employee = mapper.checkName((String)principal);
        if(employee!=null){
//            return new SimpleAuthenticationInfo(employee.getName(),employee.getPassword(),"crmRealm");
            //加盐验证
            return new SimpleAuthenticationInfo(employee.getName(),employee.getPassword(), ByteSource.Util.bytes(employee.getName()),"cremRealm");
        }
        return null;
    }

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }
}
